package com.qh.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConvertUtil {

	public static String date2String(Date date, String pattern) {

		DateFormat dateFormat = new SimpleDateFormat(pattern);

		return dateFormat.format(date);
	}

	public static Date string2Date(String date, String pattern) {

		DateFormat dateFormat = new SimpleDateFormat(pattern);
		try {
			return dateFormat.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	// yyyy-MM-dd
	// MM-dd-yyyy
	// yyyy/MM/dd
	// MM/dd/yyyy 
	public static String dateFormat(String date, String pattern) {

		if (isNotEmpty(date) && (date.contains("-") || date.contains("/"))) {

			String[] ymd = null;

			if (date.contains("-")) {
				ymd = date.split("-");
			} else if (date.contains("/")) {
				ymd = date.split("/");
			}

			if (ymd != null && ymd.length == 3) {

				String yyyyMMdd = "";

				if (ymd[0].length() == 4) {

					yyyyMMdd = ymd[0] + "/" + ymd[1] + "/" + ymd[2];
				} else {

					yyyyMMdd = ymd[2] + "/" + ymd[0] + "/" + ymd[1];
				}

				try {

					Date tmpDate = string2Date(yyyyMMdd, "yyyy/MM/dd");
					if (isNotEmpty(pattern)) {

						return date2String(tmpDate, pattern);
					}
				} catch (Exception e) {
				}
			}
		}

		return date;
	}

	public static boolean isEmpty(String target) {

		return (target == null || target.trim().length() == 0);
	}

	public static boolean isNotEmpty(String target) {

		return (target != null && target.trim().length() != 0);
	}
	
	public static String linefeed(String str) {

		return str == null ? str : str.replaceAll("\r\n", "<br>");
	}
}
